import cv2
import pytesseract
import numpy
from PIL import Image,ImageDraw,ImageFont

pytesseract.pytesseract.tesseract_cmd = r"换成你的路径"
img = cv2.imread("text.png")
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

#绘制中文
def cv2ImgText(img, text, left, top, textColor=(0, 255, 0), textSize=30):
    if (isinstance(img, numpy.ndarray)):  #判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)

#字符的识别
text = pytesseract.image_to_string(img,lang='chi_sim')

#字符的标定
# boxes = pytesseract.image_to_boxes(img,lang='chi_sim')
# H,W,C = img.shape
# for b in boxes.splitlines():
#     b = b.split(" ")
#     x1,y1,x2,y2 = int(b[1]),int(b[2]),int(b[3]),int(b[4])
#     cv2.rectangle(img,(x1,H-y1),(x2,H-y2),(0,0,255),2)
#     img = cv2ImgText(img,b[0],x1,H-y1)

#识别单词
boxes = pytesseract.image_to_data(img,lang='chi_sim')
for x ,b in enumerate(boxes.splitlines()):
    b = b.split()
    if x != 0:
        if(len(b) == 12):
            x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])
            cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
            img = cv2ImgText(img, b[11], x, y-20)

cv2.imshow("text",img)
cv2.waitKey(0)
